package com.itheima.service.impl;

import com.itheima.common.R;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import com.itheima.pojo.PageBean;
import com.itheima.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 小帅蓝
 * @Date 2022/6/12 13:38
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee login(Employee employee) {
        return employeeMapper.login(employee);
    }

    @Override
    public R<Employee> addEmployee(Employee employee) {
        int result = employeeMapper.addEmployee(employee);
        if (result > 0) {
            return R.success(employee);
        } else {
            return R.error("添加员工失败！");
        }
    }

    @Override
    public Integer getCount(String name) {
        Integer count = employeeMapper.getCount(name);
        if (count == null) {
            return -1;
        } else {
            return employeeMapper.getCount(name);
        }
    }

    @Override
    public PageBean queryAll(String name, Integer page, Integer pageSize) {
        Integer offset = getOffset(page, pageSize);
        Integer total = getCount(name);
        List<Employee> employeeList = employeeMapper.queryLimitName(name, offset, pageSize);
        return new PageBean(employeeList, total, pageSize, page);
    }

    @Override
    public Employee queryById(String id) {
        return employeeMapper.queryById(id);
    }

    @Override
    public R<Employee> updateEmployee(Employee employee) {
        int result = employeeMapper.updateEmployee(employee);
        if (result > 0) {
            return R.success(employee);
        } else {
            return R.error("修改失败！");
        }
    }

    /**
     * 从第几条开始，offset - pageSize
     *
     * @param page     当前页
     * @param pageSize 每页条数
     * @return 每页起始数
     */
    public Integer getOffset(Integer page, Integer pageSize) {
        return (page - 1) * pageSize;
    }

}
